package cn.hpclub.server.util;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

import sun.misc.BASE64Encoder;

public class DESCrypto {

    private static String       encoding     = "ASCII";
	private static final String special_char = "%(?![0-9a-fA-F]{2})";
	
	// 解密数据
	public static String decrypt(String message, String key) throws Exception {
        byte[] bytesrc = convertHexString(message.toUpperCase());
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		DESKeySpec desKeySpec = new DESKeySpec(key.getBytes(encoding));
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
		IvParameterSpec iv = new IvParameterSpec(key.getBytes(encoding));
		cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
		byte[] retByte = cipher.doFinal(bytesrc);
        return new String(retByte).replaceAll(special_char, "%25");
	}

	public static byte[] encrypt(byte[] message, String key) throws Exception {
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		DESKeySpec desKeySpec = new DESKeySpec(key.getBytes(encoding));
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
		IvParameterSpec iv = new IvParameterSpec(key.getBytes(encoding));
		cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
		return cipher.doFinal(message);
	}

    public static byte[] convertHexString(String ss){
		byte digest[] = new byte[ss.length() / 2];
		for (int i = 0; i < digest.length; i++) {
			String byteString = ss.substring(2 * i, 2 * i + 2);
			int byteValue = Integer.parseInt(byteString, 16);
			digest[i] = (byte) byteValue;
		}
		return digest;
	}

    // public static void main(String[] args) throws Exception{
//        String key = "VBZ0NR";
//        String value = "dzgadmin0.123456789.!@#$%^&*()";
//
//        byte[] bytes = value.getBytes(encoding);
//        String newKey = string2MD5(key).substring(0, 8).toUpperCase();
//        String a = toHexString(encrypt(bytes, newKey)).toUpperCase();
//        System.out.println("加密后的数据为:" + a);
//
//        String b = java.net.URLDecoder.decode(decrypt(a, newKey), encoding);
//        System.out.println("解密后的数据:" + b);
//
//        String res = encryptPassword(value, key);
//
//        System.out.println("res:" + res);
    // }

	public static String encryptPassword(String password, String key) throws Exception{
		byte[] bytes = password.getBytes(encoding);
		String newKey = DigestUtils.md5Hex(key).substring(0, 8).toUpperCase();
		
		String result = toHexString(encrypt(bytes, newKey)).toUpperCase();
		
		return result;
	}
	
	public static String toHexString(byte b[]) {
		StringBuffer hexString = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			String plainText = Integer.toHexString(0xff & b[i]);
			if (plainText.length() < 2)
				plainText = "0" + plainText;
			hexString.append(plainText);
		}
		return hexString.toString();
	}
	
	
	/*** 
     * MD5加码 生成32位md5码 
     */  
    public static String string2MD5(String inStr){  
        MessageDigest md5 = null;  
        try{  
            md5 = MessageDigest.getInstance("MD5");  
        }catch (Exception e){  
            // System.out.println(e.toString());
            e.printStackTrace();  
            return "";  
        }  
        char[] charArray = inStr.toCharArray();  
        byte[] byteArray = new byte[charArray.length];  
  
        for (int i = 0; i < charArray.length; i++)  
            byteArray[i] = (byte) charArray[i];  
        byte[] md5Bytes = md5.digest(byteArray);  
        StringBuffer hexValue = new StringBuffer();  
        for (int i = 0; i < md5Bytes.length; i++){  
            int val = ((int) md5Bytes[i]) & 0xff;  
            if (val < 16)  
                hexValue.append("0");  
            hexValue.append(Integer.toHexString(val));  
        }  
        return hexValue.toString();  
  
    }

    public static String encryptZSK(String data) throws Exception{
        return new BASE64Encoder().encode(encryptZSK(data.getBytes(), "zhangshangweike0".getBytes()));
    }

    private static byte[] encryptZSK(byte[] data, byte[] key) throws Exception{
        // 生成一个可信任的随机数源
        SecureRandom sr = new SecureRandom();

        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);

        // 创建一个密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey securekey = keyFactory.generateSecret(dks);

        // Cipher对象实际完成加密操作
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

        // 用密钥初始化Cipher对象
        cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);

        return cipher.doFinal(data);
    }

    public static String decryptRedirect(String data, String key) throws IOException, Exception{
        if(data == null)
            return null;
        byte[] buf = Base64.decodeBase64(data);
        byte[] bt = decryptRedirect(buf, key.getBytes());
        return new String(bt);
    }

    private static byte[] decryptRedirect(byte[] data, byte[] key) throws Exception{
        // 生成一个可信任的随机数源
        SecureRandom sr = new SecureRandom();

        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);

        // 创建一个密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey securekey = keyFactory.generateSecret(dks);

        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance("DES");

        // 用密钥初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, securekey, sr);

        return cipher.doFinal(data);
    }

}
